<?php

/**
 * @require xdom class, xnode class
 */
class rss_creator
{

	const date_format = "D, d M Y H:i:s O";

	/**
	 * @var xdom
	 */
	protected $rss_xdom;

	/**
	 * @var xnode
	 */
	protected $channel_node;

	protected $plugins = array();

	public function __construct($title, $link, $description, $language, $copyright, $create_yandex_image_node = false, $yandex_image_url = null, $yandex_image_title = null, $yandex_image_link = null, $pub_date_timestamp_or_string = null)
	{
		$this->rss_xdom = xdom::create("rss");
		$this->rss_xdom->set_attr("version", "2.0");
		$this->channel_node = $this->rss_xdom->create_child_node("channel");
		$this->channel_node->create_child_node("title", $title);
		$this->channel_node->create_child_node("link", $link);
		$this->channel_node->create_child_node("description", $description);
		if ($create_yandex_image_node)
		{
			$image_node = $this->channel_node->create_child_node("image");
			$image_node->create_child_node("url", $yandex_image_url);
			$image_node->create_child_node("title", $yandex_image_title);
			$image_node->create_child_node("link", $yandex_image_link);
		}
		$this->channel_node->create_child_node("language", $language);
		$this->channel_node->create_child_node("copyright", $copyright);
		$this->channel_node->create_child_node("pubDate", $this->get_date_string($pub_date_timestamp_or_string));
		$this->channel_node->create_child_node("generator", "IntCMF RSS generator (http://intcmf.com)");
		$this->channel_node->create_child_node("docs", "http://blogs.law.harvard.edu/tech/rss");
	}

	public function add_plugin(rss_creator_plugin $rss_creator_plugin)
	{
		$this->plugins[] = $rss_creator_plugin;
		$rss_creator_plugin->modify_rss_node($this->rss_xdom);
		$rss_creator_plugin->modify_channel_info($this->channel_node);
	}

	public function add_item_node($data)
	{
		$item_node = $this->channel_node->create_child_node("item");
		$item_node->create_child_node("title", $data["title"]);
		$item_node->create_child_node("link", $data["link"]);
		$item_node->create_child_node("description", $data["description"]);
		$item_node->create_child_node("pubDate", $this->get_date_string(isset($data["pub_date"]) ? $data["pub_date"] : $data["pubDate"]));
		foreach ($this->plugins as $plugin)
		{
			/* @var $plugin rss_creator_plugin */
			$plugin->modify_item_node($item_node, $data);
		}
		return $item_node;
	}

	/**
	 * @return string
	 */
	public function get_rss_xml()
	{
		return $this->rss_xdom->get_xml();
	}

	/**
	 * @return xdom
	 */
	public function get_rss_xdom()
	{
		return $this->rss_xdom;
	}

	protected function get_date_string($pub_date_timestamp_or_string)
	{
		if (is_null($pub_date_timestamp_or_string))
		{
			return date(self::date_format);
		}
		elseif (is_int($pub_date_timestamp_or_string))
		{
			return date(self::date_format, $pub_date_timestamp_or_string);
		}
		else
		{
			return (string)$pub_date_timestamp_or_string;
		}
	}

}

?>